package com.hzc.springchan.service.impl;

import com.hzc.springchan.bean.entity.UserOperationEntity;
import com.hzc.springchan.mapper.UserOperationMapper;
import com.hzc.springchan.service.IOperationLogService;
import com.hzc.springchan.strategy.operationlog.OperationLogContext;
import com.hzc.springchan.util.JSONUtils;
import com.hzc.springchan.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: 操作记录服务类
 * @Author: chen990627
 * @Date: 2022/11/05
 **/
@Service
public class OperationLogServiceImpl implements IOperationLogService {

    @Autowired
    private UserOperationMapper userOperationMapper;

    @Autowired
    private OperationLogContext operationLogContext;

    @Override
    public void logOperation(OperationRequest operationRequest) {

        UserOperationEntity entity = new UserOperationEntity();
        entity.setUserId(operationRequest.getUserId());
        entity.setOperation(
                operationLogContext.generateOperation(operationRequest.getOperation(), operationRequest.getParamMap())
        );

        if (entity.getOperation() == null) {
            return;
        }

        try {
            userOperationMapper.save(entity);
        } catch (Exception e) {
            LogUtils.error("user operation log exception: {}", e);
            return;
        }

        if (entity.getId() == null) {
            LogUtils.error("user operation log fail: {}", JSONUtils.toJSON(entity));
        }
    }
}
